//
//  LTCreateGroupViewController.m
//  LearnTeacher
//
//  Created by zyl on 2024/4/11.
//

#import "LTCreateGroupViewController.h"
#import "LTCLassDetailGroupModel.h"
#import "LTCLassDetailStudentModel.h"
#import "LTClassAPIManager.h"
#import "LTGroupDeleteAlertView.h"
@interface LTCreateGroupViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic ,strong)UICollectionView *collection;

@property(nonatomic ,strong)UIButton *finishButton;

@property(nonatomic ,strong)UITextField *nameTextFiled;

@property(nonatomic ,strong)NSMutableArray *selectedStudentsArray;

@property(nonatomic ,strong)NSMutableArray *allStudentsArray;

@property(nonatomic ,strong)LTCLassDetailGroupModel *groupModel;

@property(nonatomic ,strong)LTGroupDeleteAlertView *alertView;
@end

@implementation LTCreateGroupViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:LTClearColor] backgroundColor:LTClearColor shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(0, 0, 0, 1),NSFontAttributeName:MFontWithSize(17)} enableScrollEdgeAppearance:YES];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新建分组";
    // Do any additional setup after loading the view.
    [self setBackButtonIsHidden:NO];
    [self.view addSubview:self.finishButton];
    [self.collection reloadData];
    self.selectedStudentsArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.allStudentsArray = [[NSMutableArray alloc] initWithCapacity:0];
    [self.allStudentsArray addObjectsFromArray:self.groupModel.student];
    if (self.groupModel.group_id.length > 0) {
        self.title = @"编辑分组";
        [self createRightBarButtonItem];
        self.nameTextFiled.text = self.groupModel.name;
        [self.selectedStudentsArray addObjectsFromArray:self.groupModel.student];
    }
    
}
- (void)createRightBarButtonItem
{
    UIButton *button =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 44)];
    button.titleLabel.font =RFontWithSize(16);
    [button setTitle:@"删除" forState:UIControlStateNormal];
    [button setTitleColor:rgba(41, 121, 255, 1) forState:UIControlStateNormal];
    [button addTarget:self action:@selector(deleteGroupClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItems =@[item];
}
 -(void)deleteGroup
{
    
    [LTClassAPIManager deleteGroupWithParam:@{@"id":self.groupModel.group_id} result:^(NSDictionary * _Nonnull dic) {
        [self backPop];
    }];
}
-(void)deleteGroupClick
{
    self.alertView.titleLab.text = [NSString stringWithFormat:@"确定删除 %@ 分组吗？",self.groupModel.name];
    self.alertView.hidden = NO;
}
 -(void)finishButtonAction
{
    if (self.nameTextFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"输入小组名称"];
        return;
    }
    NSString *ids = @"";
    for (LTCLassDetailStudentModel *sModel in self.selectedStudentsArray) {
        if (ids.length == 0) {
            ids = sModel.student_id;
        }else{
            ids = [NSString stringWithFormat:@"%@,%@",ids,sModel.student_id];
        }
    }
    NSMutableDictionary *dic = @{@"name":self.nameTextFiled.text,@"student_ids":ids,@"class_id":self.groupModel.class_id}.mutableCopy;
    if (self.groupModel.group_id.length > 0) {
        [dic setObject:self.groupModel.group_id forKey:@"id"];
    }
    
    [LTClassAPIManager addGroupWithParam:dic result:^(NSDictionary * _Nonnull dic) {
        [self backPop];
    }];
}
- (void)selectAllOrNot:(UIButton *)button
{
    button.selected = !button.selected;
    [self.selectedStudentsArray removeAllObjects];
    if (button.selected) {
        [self.selectedStudentsArray addObjectsFromArray:self.allStudentsArray];
    }
    [self.collection reloadData];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.allStudentsArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell removeAllSubviews];
    LTCLassDetailStudentModel *sModel= self.allStudentsArray[indexPath.item];
    UIButton *clickBtn =  ({
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = MFontWithSize(16);
        [button setTitle:sModel.username forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"ic_class_demain"] forState:UIControlStateNormal];
        button.adjustsImageWhenHighlighted = NO;
        [button layoutButtonWithEdgeInsetsStyle:LButtonEdgeInsetsStyleRight imageTitleSpace:6];
        button.userInteractionEnabled = NO;
        [button setFrame:CGRectMake(0, 0, (LTScreenWidth - 32 - 24)/3.00, 46)];
        button;
        
    });
   
    
    [cell setBackgroundColor:LTClearColor];
    UIColor *titleColor = LTTextBlack;
    UIColor *bgColor = LTWhiteColor;
    clickBtn.layer.cornerRadius = 7;
    clickBtn.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:50/255.0 blue:83/255.0 alpha:0.0500].CGColor;
    clickBtn.layer.shadowOffset = CGSizeMake(0,2);
    clickBtn.layer.shadowOpacity = 1;
    clickBtn.layer.shadowRadius = 12;
    clickBtn.layer.borderWidth = 0;
    if ([self.selectedStudentsArray containsObject:sModel]) {
        
        bgColor = rgba(41, 121, 255, 0.10);
        titleColor = rgba(41, 121, 255, 1);
        
        clickBtn.layer.borderWidth = 1;
        clickBtn.layer.borderColor = [UIColor colorWithRed:41/255.0 green:121/255.0 blue:255/255.0 alpha:1.0].CGColor;
        clickBtn.layer.cornerRadius = 7;
        clickBtn.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:50/255.0 blue:83/255.0 alpha:0.0500].CGColor;
        clickBtn.layer.shadowOffset = CGSizeMake(0,2);
        clickBtn.layer.shadowOpacity = 1;
        clickBtn.layer.shadowRadius = 12;
    }
    [clickBtn setTitleColor:titleColor forState:UIControlStateNormal];
    clickBtn.backgroundColor = bgColor;
    [cell addSubview:clickBtn];
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake( (LTScreenWidth - 32 - 24)/3.00, 46);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 16, 0, 16);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(LTScreenWidth, 136);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 12;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];

    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        [header removeAllSubviews];
        
        UIView *contentView = [[UIView alloc] init];
        contentView.frame = CGRectMake(16,16,LTScreenWidth - 32,62);
        contentView.layer.borderWidth = 1;
        contentView.layer.borderColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
        contentView.layer.backgroundColor = [UIColor colorWithRed:74/255.0 green:144/255.0 blue:246/255.0 alpha:0.1000].CGColor;
        contentView.layer.cornerRadius = 12;
        contentView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.0500].CGColor;
        contentView.layer.shadowOffset = CGSizeMake(0,2);
        contentView.layer.shadowOpacity = 1;
        contentView.layer.shadowRadius = 12;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEdit)];
        [contentView addGestureRecognizer:tap];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 60, 62)];
        titleLabel.font = MFontWithSize(15);
        titleLabel.text = @"小组名称";
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        titleLabel.textColor = LTTextBlack;
        [contentView addSubview:titleLabel];
        [contentView addSubview:self.nameTextFiled];
        
        UIButton *clickBtn =  ({
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.titleLabel.font = MFontWithSize(16);
            [button setTitle:@"全选" forState:UIControlStateNormal];
            [button setTitleColor:LTTextBlack forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_protocol_unSelect"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_protocol_select"] forState:UIControlStateSelected];
            button.adjustsImageWhenHighlighted = NO;
            [button layoutButtonWithEdgeInsetsStyle:LButtonEdgeInsetsStyleLeft imageTitleSpace:8];
            [button setFrame:CGRectMake(LTScreenWidth - 24 - 52, contentView.bottom + 20, 52, 26)];
            [button addTarget:self action:@selector(selectAllOrNot:) forControlEvents:UIControlEventTouchUpInside];
            button;
            
        });
        [self.finishButton setTitle:[NSString stringWithFormat:@"完成 (已选%lu个学生)",(unsigned long)self.selectedStudentsArray.count] forState:UIControlStateNormal];
        clickBtn.selected = self.selectedStudentsArray.count == self.allStudentsArray.count;
        UILabel *titleLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(24, contentView.bottom + 24, 55, 18)];
        titleLabel2.font = RFontWithSize(13);
        titleLabel2.text = @"未分组";
        [titleLabel2 setTextAlignment:NSTextAlignmentCenter];
        titleLabel2.textColor = LTWhiteColor;
        titleLabel2.backgroundColor = rgba(83, 102, 135, 0.75);
        [titleLabel2 setAllCornersWithCornerRadius:4];
        
        [contentView addSubview:titleLabel];
        [contentView addSubview:self.nameTextFiled];
        
        [header addSubview:titleLabel2];
        [header addSubview:clickBtn];
        [header addSubview:contentView];
        
    }
    return header;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LTCLassDetailStudentModel *sModel= self.allStudentsArray[indexPath.item];
    if ([self.selectedStudentsArray containsObject:sModel]) {
        [self.selectedStudentsArray removeObject:sModel];
    }else{
        [self.selectedStudentsArray addObject:sModel];
    }
    [self.collection reloadData];
}
- (UICollectionView *)collection
{
    if (!_collection) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        //layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, LTTopBarHeight, LTScreenWidth,LTScreenHeight - LTTopBarHeight - LTBottomDangerousAreaHeight - 60) collectionViewLayout:layout];
        _collection.dataSource = self;
        _collection.delegate = self;
        _collection.backgroundColor = LTClearColor;
        _collection.y = 0;
        [_collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [_collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        
        [self.view addSubview:_collection];
    }
    
    return _collection;
}
-(UIButton *)finishButton
{
    if (!_finishButton)
    {
        _finishButton = [UIButton new];
        _finishButton.frame =CGRectMake(32, LTScreenHeight - LTBottomDangerousAreaHeight - 60, LTScreenWidth - 64, 44);
       
        [_finishButton setTitle:@"完成 (已选9个学生)" forState:UIControlStateNormal];
       // [_finishButton setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateNormal];
        [_finishButton setTitleColor:LTWhiteColor forState:UIControlStateNormal];
        [_finishButton.titleLabel setFont:MFontWithSize(14)];
        [_finishButton addTarget:self action:@selector(finishButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _finishButton.backgroundColor = rgba(41, 121, 255, 1);
        _finishButton.layer.cornerRadius = 22;
        _finishButton.layer.shadowColor = rgba(41, 121, 255, 0.50).CGColor;
        _finishButton.layer.shadowOffset = CGSizeMake(0,4);
        _finishButton.layer.shadowOpacity = 1;
        _finishButton.layer.shadowRadius = 6;
    }
    
    return _finishButton;
}
-(UITextField *)nameTextFiled
{
    if (!_nameTextFiled)
    {
        _nameTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(90, 6, LTScreenWidth - 32 - 80 - 20 - 10, 49)];
        _nameTextFiled.font = MFontWithSize(16);
        _nameTextFiled.textColor = rgba(51, 51, 51, 1);
        _nameTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _nameTextFiled.textAlignment = NSTextAlignmentRight;
        _nameTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"输入小组名称" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _nameTextFiled.delegate = self;
        _nameTextFiled.returnKeyType = UIReturnKeyDone;
        if (@available(iOS 11.0,*)) {
            _nameTextFiled.textContentType =UITextContentTypeUsername;
        }
       
   
    }

    return _nameTextFiled;
}
- (LTGroupDeleteAlertView *)alertView
{
    if (!_alertView) {
        _alertView = [[NSBundle mainBundle] loadNibNamed:@"LTGroupDeleteAlertView" owner:nil options:nil].lastObject;
        _alertView.hidden = YES;
        WeakSelf(self);
        _alertView.block = ^{
            [weakself deleteGroup];
        };
        [self.navigationController.tabBarController.view addSubview:_alertView];
    }
    return _alertView;
}
- (void)setParaObject:(NSObject *)paraObject
{
    self.groupModel = (LTCLassDetailGroupModel *)paraObject;
    
}
@end
